using NodeCanvas;
using NodeCanvas.DialogueTrees;
using UnityEngine;

public class DialogueSubtitlesGUI : MonoBehaviour
{
	public GUISkin skin;

	public bool showOverActor;

	private DialogueActor talkingActor;

	private string displayText;

	private void Awake()
	{
		EventHandler.Subscribe(this, DLGEvents.OnActorSpeaking);
		EventHandler.Subscribe(this, DLGEvents.OnDialogueStarted);
		EventHandler.Subscribe(this, DLGEvents.OnDialogueFinished);
		EventHandler.Subscribe(this, DLGEvents.OnDialoguePaused);
		base.enabled = false;
		GetComponent<DialogueTree>().StartGraph();
	}

	private void OnActorSpeaking(DialogueSpeechInfo speech)
	{
		base.enabled = true;
		talkingActor = speech.actor;
		StartCoroutine(talkingActor.ProcessStatement(speech.statement, speech.Continue));
	}

	private void OnDialogueStarted(DialogueTree dialogue)
	{
	}

	private void OnDialoguePaused()
	{
		OnDialogueFinished();
	}

	private void OnDialogueFinished()
	{
		StopAllCoroutines();
		displayText = null;
		base.enabled = false;
		if ((bool)talkingActor)
		{
			talkingActor.speech = null;
		}
	}

	private void OnGUI()
	{
		GUI.skin = skin;
		if ((bool)talkingActor)
		{
			displayText = talkingActor.speech;
		}
		if (string.IsNullOrEmpty(displayText) || !Camera.main)
		{
			base.enabled = false;
			return;
		}
		Vector2 vector = new GUIStyle("box").CalcSize(new GUIContent(displayText));
		Rect position = new Rect(0f, 0f, 0f, 0f);
		position.width = vector.x;
		position.height = vector.y;
		Vector3 vector2 = Camera.main.WorldToScreenPoint(talkingActor.dialoguePosition);
		vector2.y = (float)Screen.height - vector2.y;
		if (showOverActor && Camera.main.rect.Contains(new Vector2(vector2.x / (float)Screen.width, vector2.y / (float)Screen.height)))
		{
			Vector2 center = position.center;
			center.x = vector2.x;
			center.y = vector2.y - position.height / 2f;
			position.center = center;
		}
		else
		{
			position = new Rect(10f, Screen.height - 60, Screen.width - 20, 50f);
			Rect position2 = new Rect(0f, 0f, 200f, 28f);
			Vector2 center2 = position2.center;
			center2.x = position.center.x;
			center2.y = position.y - 24f;
			position2.center = center2;
			GUI.Box(position2, talkingActor.actorName);
			if ((bool)talkingActor.portrait)
			{
				Rect position3 = new Rect(10f, Screen.height - talkingActor.portrait.height - 70, talkingActor.portrait.width, talkingActor.portrait.height);
				GUI.DrawTexture(position3, talkingActor.portrait);
			}
		}
		GUI.Box(position, displayText);
	}
}
